<template>
  <div class="Featured">
    <div class="page-head no-pl">
      <div class="page-tool width-block">
        <div class="page-tool-left">
          <el-select
            class="tool-sel"
            placeholder="类型筛选"
            v-model="featured_type"
            clearable
          >
            <el-option
              v-for="item in featuredTypes"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            ></el-option>
          </el-select>
          <search-input placeholder="推荐位名称" @search="searchChange" />
        </div>
        


        <!--  -->
        <div
          class="tool-btn"
          v-if="$permiss(btnPermiss, '新增')"
          @click="open('add')"
        >
          新 增
        </div>
      </div>
    </div>
    
    <div class="page-body">
      <div class="media-list">
        <el-scrollbar class="scroll-bar">
          <el-row>
            <el-col v-for="(item, i) in list" :key="i" :span="6">
              <div class="media-box">
                <div class="media-con">
                  <div class="media-pic res-pic">
                    <img :src="item.cover_url" class="thumb-img" />
                  </div>
                  
                  <div class="media-content res-content">
                    <el-tooltip
                      effect="dark"
                      :content="item.name"
                      placement="left"
                    >
                      <div class="media-name">
                        {{ item.name }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="media-row res-row">
                    <div class="key">内容类型</div>
                    <el-tooltip
                      effect="dark"
                      :content="
                        conTypes.find((v) => v.key === item.content_type).value
                      "
                      placement="left"
                    >
                      <div class="val">
                        {{
                          conTypes.find((v) => v.key === item.content_type).value
                        }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="media-row res-row">
                    <div class="key">简介</div>
                    <el-tooltip
                      effect="dark"
                      :content="item.remark"
                      placement="left"
                    >
                      <div class="val">
                        {{ item.remark }}
                      </div>
                    </el-tooltip>
                  </div>
                </div>
                <div class="media-foot res-foot res-media">

                  <div
                    v-if="$permiss(btnPermiss, '内容')"
                    class="txt-btn spe-btn primary"
                    @click="openCon(item)"
                  >
                    内容
                  </div>
                  <!--  -->
                  <div
                    v-if="$permiss(btnPermiss, '修改')"
                    class="txt-btn spe-btn primary"
                    @click="open('edit', item)"
                  >
                    修改
                  </div>
                  <!--  -->
                  <div
                    v-if="$permiss(btnPermiss, '删除')"
                    class="txt-btn spe-btn error"
                    @click="doDelete(item)"
                  >
                    删除
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-scrollbar>
      </div>

    </div>
    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="450px"
      :title="model.type === 'add' ? '新增推荐位' : '修改推荐位'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="推荐位名称" class="required">
            <el-input
              name="featuredName"
              v-model="form.name"
              v-validate="'required'"
              maxlength="6"
              show-word-limit
            />
            <div v-show="errors.has('featuredName')" class="el-form-item__error">
              {{ errors.first("featuredName") }}
            </div>
          </el-form-item>
          <el-form-item label="推荐类型">
            <el-radio-group v-model="form.featured_type">
              <el-radio
                v-for="item in featuredTypes"
                :label="item.key"
                :key="item.key"
                >
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="内容类型">
            <el-radio-group v-model="form.content_type">
              <el-radio
                v-for="item in conTypes"
                :label="item.key"
                :key="item.key"
                >
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.content_type==0" key="res" label="" class="upload-form-item">
            <div @click="openSelect">
              <el-input
                v-model="chosenTxt"
                :readonly="true"
                name="hasChosen"
                v-validate="'hasChosen'"
                placeholder="请选择资源"
              />
              <img src="~assets/img/pick.png" class="pick-img">
            </div>
            <div v-show="errors.has('hasChosen')" class="el-form-item__error">
              {{ errors.first("hasChosen") }}
            </div>
          </el-form-item>
          <el-form-item v-else-if="form.content_type==1" key="url" label="">
            <el-input
              v-model="linkUrl"
              placeholder="请输入外链地址"
              name="linkUrl"
              v-validate="'required|http'"
              maxlength="964"
            />
            <div v-show="errors.has('linkUrl')" class="el-form-item__error">
              {{ errors.first("linkUrl") }}
            </div>
          </el-form-item>

          <el-form-item label="封面图片" class="required">
            <el-upload
              v-validate="'required'"
              v-model="form.cover_url"
              name="cover_url"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadReq"
              :accept="imgAccept"
            >
              <img
                v-if="form.cover_url"
                key="pic"
                :src="form.cover_url"
                class="upload-img"
              />
              <img
                v-else
                key="default"
                src="~assets/img/upload.png"
                class="upload-img"
              />
            </el-upload>
            <div v-show="errors.has('cover_url')" class="el-form-item__error">
              {{ errors.first("cover_url") }}
            </div>
          </el-form-item>
          <el-form-item label="简介">
            <el-input
              type="textarea"
              v-model.trim="form.remark" 
              maxlength="32"
              show-word-limit
            />
          </el-form-item>
          
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
    
    <!-- 更改外链弹框 -->
    <el-dialog
      :visible.sync="conVisable"
      width="450px"
      title="更改外链"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="外链地址" required>
            <el-input
              v-model="linkUrl"
              placeholder="请输入外链地址"
              maxlength="964"
            />
            <div v-show="!linkUrlOk" class="el-form-item__error">
              {{linkUrl ? '外链地址格式不正确' : '外链地址不能为空'}} 
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="conClose">取 消</el-button>
        <el-button type="primary" @click="conSubmit">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>{{txt}}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="featuredDelete">确 定</el-button>
      </span>
    </el-dialog>

    <application-select
      v-if="selectVisable"
      @cancel="appCancel"
      :resource_ids="resource_ids"
      mode="single"
      @sure="appSure"
    />
  </div>
</template>

<script>
import { Loading } from "element-ui";
import { format } from "silly-datetime";
import * as api from "@/api";
import { imgAccept } from "@/consts/consts";
import { featuredTypes, conTypes } from "@/consts/codesMap";
import { featuredFormKey } from "@/consts/formKey";
import client from "@/utils/oss";

export default {
  data() {
    return {
      btnPermiss: [],
      featured_type: '',
      imgAccept,
      list: [],
      format,
      search: "",
      model: {
        type: "add",
        visible: false,
      },
      txt: '确定删除该条数据？',
      featured_id: "",
      featuredTypes,
      conTypes,
      form: { ...featuredFormKey },
      chosenTxt: `已选择0个资源`,
      selectVisable: false,
      conVisable: false,
      linkUrl: '',
      uploadFile: null,
      resource_select: [],
      resource_ids: [],
      visibility: false,
      loading: null
    };
  },

  watch: {
    featured_type() {
      this.featuredList()
    }
  },
  
  computed: {
    linkUrlOk() {
      return /^https?:\/\/(.*)/ .test(this.linkUrl)
    }
  },

  methods: {
    open(type, row = null) {
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in featuredFormKey) {
          this.form[k] = row[k];
        }
        this.featured_id= row.featured_id;
        if (row.content_type == 0) {
          this.resource_ids = [row.content]
          this.chosenTxt = `已选择1个资源`
        } else if (row.content_type == 1) {
          this.linkUrl = row.content
        }
      } else {
        this.chosenTxt = `已选择0个资源`
        this.linkUrl = ''
        this.resource_select = []
        this.resource_ids = []
        setTimeout(() => {
          this.$validator.reset()
        }, 100)
      }
      this.model.visible = true;
    },

    doDelete(row) {
      this.featured_id = row.featured_id;
      this.visibility = true;
    },

    openSelect() {
      this.selectVisable = true
    },

    appCancel() {
      this.selectVisable = false;
      
    },

    appSure(data) {
      if (data.length < 1) {
        this.$message.warning('至少选择一个资源！')
      } else {
        if (this.model.visible) {
          this.chosenTxt = `已选择${data.length}个资源`
          this.resource_select = data;
          this.resource_ids = data.map(item => item.res_id)
          this.selectVisable = false;
        } else {
          let arr = data.map(item => item.res_id)
          let [con] = arr
          this.featuredUpdateContent(con)
        }
      }
    },

    openCon({content_type, content, featured_id}) {
      this.featured_id = featured_id
      if (content_type === 0) {
        this.resource_ids = [content]
        this.selectVisable = true
      } else if (content_type === 1) {
        this.linkUrl = content
        this.conVisable = true
      } else {
        this.$message.warning('暂无内容！')
      }
    },

    conClose() {
      this.featured_id = ''
      this.conVisable = false
    },

    conSubmit() {
      if (this.linkUrlOk) {
        let con = this.linkUrl
        this.featuredUpdateContent(con)
      }
    },

    searchChange(e) {
      this.search = e;
      this.featuredList();
    },

    beforeAvatarUpload(file) {
      const typeOk = ['image/png', 'image/PNG', 'image/jpg', 'image/JPG', 'image/jpeg', 'image/JPEG'].includes(file.type)
      if (typeOk) {
        this.uploadFile = file;
        return true;
      } else {
        return this.$message.warning('只支持png、jpg格式的图片')
      }
    },

    close() {
      this.model.visible = false;
      this.form = { ...featuredFormKey };
      this.resource_select = []
      this.resource_ids = []
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },
    
    async uploadReq() {
      let arr = this.uploadFile.name.split(".")
      let [suf, ...rest] = [...arr].reverse()
      let n = rest.reverse().join('.')
      let fileName = `${n}_${+new Date()}.${suf}`;
      this.fileName = fileName
      this.loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      let result = await client.put(`app/${fileName}`, this.uploadFile);

      if (result) {
        this.form.cover_url = result.res.requestUrls[0];
        this.loading.close();
      }

      // this.ossPolicy()
    },

    
    async ossPolicy() {
      const { code, data } = await api.dropdown(this).ossPolicy({
        dir: 'resource'
      });
      if (code === 0) {
        let formData = new FormData()
        formData.append('key', `resource/${this.fileName}`) // 存储在oss的文件路径
        formData.append('OSSAccessKeyId', data.accessId) // //accessKeyId
        formData.append('policy', data.policy) // policy
        formData.append('Signature', data.signature) //签名
        formData.append('success_action_status', 200)
        formData.append('file', this.uploadFile, this.fileName)
        this.$axios.post(data.host, formData, {
          headers: { 
            'Content-Type': 'multipart/form-data'
          },
        }).then(res => {
          this.form.cover_url = `${data.host}/resource/${this.fileName}`
          this.loading.close();
        })
      }
    },

    async featuredList() {
      const { code, data } = await api.featured(this).featuredList({
        offset: 0,
        limit: -1,
        name: this.search,
        type: this.featured_type
      });
      if (code === 0) {
        this.list = data;
      }
    },



    async addOrEdit() {
      let fn = this.model.type === "add" ? "featuredAdd" : "featuredUpdate";
      if (this.form.content_type == 0) {
        [this.form.content] = this.resource_ids
      } else if (this.form.content_type == 1) {
        this.form.content = this.linkUrl
      } else {
        this.form.content = ''
      }
      const { code } = await api.featured(this)[fn](this.form, this.featured_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.featuredList();
      }
    },

    async featuredDelete() {
      const { code } = await api.featured(this).featuredDelete(this.featured_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.featured_id = "";
        this.visibility = false;
        this.featuredList();
      }
    },
    
    async featuredUpdateContent(con) {
      const { code } = await api.featured(this).featuredUpdateContent({
        content: con
      }, this.featured_id)
      if (code === 0) {
        this.$message.success("操作成功");
        this.conClose()
        this.selectVisable = false
        this.featuredList()
      }
    },
  },
  created() {
    this.featuredList();
    let permission = JSON.parse(localStorage.getItem("permission"))
    let curMenu = permission.find(item => item.txt === "内容管理")
    this.btnPermiss = curMenu.btns
  }
}
</script>

<style lang="stylus">
.Featured{
  
}
</style>